package com.tencent.welink.util;

import com.google.protobuf.ByteString;
import io.netty.buffer.ByteBuf;

/**
 * Created by junchihe on 2019/1/14.
 */
public class EventUtil {
    public static String getByteString(ByteString byteString) {
        if(byteString == null || byteString.isEmpty()) {
            return null;
        }
        return byteString.toStringUtf8();
    }

    public static String constructKey(String weling_id,String weling_sub_id,String weling_ssub_id) {
        StringBuilder sb = new StringBuilder();
        if(weling_id!= null) sb.append(weling_id);
        if(weling_sub_id != null)  sb.append("_").append(weling_sub_id);
        if(weling_ssub_id != null)  sb.append("_").append(weling_ssub_id);
        return sb.toString();
    }

    public static String constructKey(ByteString weling_id, ByteString weling_sub_id, ByteString weling_ssub_id) {
        return constructKey(getByteString(weling_id),getByteString(weling_sub_id),getByteString(weling_ssub_id));
    }

    public static String constructKey(String weling_id,String weling_sub_id ) {
        return constructKey(weling_id,weling_sub_id,null);
    }

    public static String constructKey(ByteString weling_id, ByteString weling_sub_id ) {
        return constructKey(weling_id,weling_sub_id,null);
    }

    public static int getEncryptByVersion(int version) {
        if(version<3) return 0;
        else return Math.min(version,4);
    }

    public static byte[] getBytes(ByteBuf buf, int totalLen, int encryptedLen, IEncryptAndDecrypt aes128) {

        byte[] bodyData = null;
        if(aes128 == null || encryptedLen <= 0 || encryptedLen>totalLen){
            bodyData = new byte[totalLen];
            buf.readBytes(bodyData);

            return  bodyData;
        }
        bodyData = new byte[encryptedLen];
        buf.readBytes(bodyData);

        bodyData = aes128.decrypt(bodyData);

        if(bodyData == null) {
            return null;
        }

        int minus = totalLen - encryptedLen;
        if(minus <= 0) return bodyData;

        byte[] copy = new byte[bodyData.length+ totalLen-encryptedLen];
        System.arraycopy(bodyData, 0, copy, 0,
                bodyData.length);
        buf.readBytes(copy,bodyData.length,totalLen-encryptedLen);
        return copy;
    }
}
